import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../../common/ScreenAdaper.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import '../../config/Config.dart';
import '../../widget/LoadingWidget.dart';
import 'package:url_launcher/url_launcher.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  // ignore: non_constant_identifier_names
  List _swiperData = [];
  List _clickHotData = [];
  List _GdData = [];
  // ignore: must_call_super
  void initState(){
    super.initState();
    _getSwiperDate();// 轮播
    _getClickHotDate(); // 点击
    _getCollectHotDate(); // 收藏
  }

  @override
  Widget build(BuildContext context) {
    S.init(context);
    return ListView(
      children: <Widget>[
        Container(
          child: _lunbo(),
        ),
        _titleWidget("猜你喜欢"),
        _shopBoxWidget(),
        _titleWidget("热门小说"),
        _listWidget(),
      ],
    );
  }

  //轮播图
  Widget _lunbo() {
    if(this._swiperData.length > 0){
      return Container(
        child: AspectRatio(
          aspectRatio: 2/1,
          child: new Swiper(
            itemBuilder: (BuildContext context, int index) {
              if(_swiperData[index]["Field"] is String && _swiperData[index]["Field"] != "") {
                _swiperData[index]["Field"] = int.parse(_swiperData[index]["Field"]);
              }
              return InkWell(
                child: Image.network(Config.domain+"${_swiperData[index]["Image"]}",fit: BoxFit.fill,),
                onTap: (){
                  if(_swiperData[index]["Type"] == "navigator"){
                    Navigator.pushNamed(context, "${_swiperData[index]["Url"]}", arguments: {
                      "bookId":_swiperData[index]["Field"]
                    });
                  } else if(_swiperData[index]["Type"] == "out"){
                    print(_swiperData[index]["Url"]);
                    _openUrl(_swiperData[index]["Url"]);
                  }
                },
              );
            },
            itemCount: _swiperData.length,
            viewportFraction: 0.8,
            scale: 0.9,
            autoplay:true,
          ),
        ),
      );
    } else {
      return Text("加载中。。。");
    }
  }

  // 打开外部浏览器
  _openUrl(String url) async{
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  // 小标题
  Widget _titleWidget(value){
    return Container(
      margin: EdgeInsets.all(S.width(20.0)),
      padding: EdgeInsets.only(left: S.width(10)),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
                color: Colors.red,
                width: S.width(4),
              )
          )
      ),
      child: Text(value,style: TextStyle(color: Colors.black54,fontSize: S.size(36)),),
    );
  }

  // 商品盒子滚动
  Widget _shopBoxWidget(){
    if(_GdData.length > 0){
      return Container(
        height: S.height(234),
        padding: EdgeInsets.all(S.width(20)),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemBuilder: (contxt,index){
            return GestureDetector(
              child: Column(
                children: <Widget>[
                  Container(
                    height: S.height(140),
                    width: S.width(140),
                    margin: EdgeInsets.only(right: S.width(21)),
                    child: Image.network("${_GdData[index]['Image']}",fit: BoxFit.cover),
                  ),
                  Container(
                    padding: EdgeInsets.only(top:S.height(10)),
                    width: S.width(140),
                    child: Text("${_GdData[index]['Name']}",style: TextStyle(color: Colors.red),overflow: TextOverflow.ellipsis,),
                  )
                ],
              ),
              onTap: () {
                Navigator.pushNamed(context, "/book",arguments:{"bookId":_GdData[index]["BookId"]});
              },
            );
          },
          itemCount: _GdData.length,
        ),
      );
    } else {
      return LoadingWidget();
    }
  }


  // 热点内容
  Widget _listWidget(){
    if(_GdData.length > 0) {
      return Column(
        children: _clickHotData.map((v) {
          return Column(
            children: [
              Container(
                margin: EdgeInsets.all(S.width(20.0)),
                child: GestureDetector(
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: S.width(200),
                        height: S.height(240),
                        child: Image.network(
                            "${v['Image']}", fit: BoxFit.cover),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          height: S.height(240),
                          margin: EdgeInsets.only(left: 10),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text("${v['Name']}", maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(fontSize: S.size(30),
                                    fontWeight: FontWeight.bold),),
                              Container(
                                padding: EdgeInsets.only(top: 1, bottom: 1),
                                child: Text("作者：${v['Author']}", maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(fontSize: S.size(28),
                                        color: Colors.black54)),
                              ),
                              Text("${v['Info']}", maxLines: 5,
                                overflow: TextOverflow.ellipsis,),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  onTap: () {
                    Navigator.pushNamed(context, "/book",arguments:{"bookId":v["BookId"]});
                  },
                ),
              ),
              Divider(height: 1,)
            ],
          );
        }).toList(),
      );
    } else {
      return LoadingWidget();
    }
  }

  //================================


  // 获取轮播图
  _getSwiperDate() async{
    var apiUrl = "${Config.domain}api/book/swiper?num=5";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    if(list['code'] == 1){
      setState(() {
        this._swiperData = list["data"];
      });
    }
  }

  // 获取热点小说
  _getClickHotDate() async{
    var apiUrl = "${Config.domain}api/book/hot_click?num=15";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    if(list['code'] == 1){
      setState(() {
        this._clickHotData = list["data"];
      });
    }
  }
  // 获取收藏量高的小说
  _getCollectHotDate() async{
    var apiUrl = "${Config.domain}api/book/hot_collect?num=10";
    Response result=await Dio().get(apiUrl);
    var list=result.data;
    if(list['code'] == 1){
      setState(() {
        this._GdData = list["data"];
      });
    }
  }
}